<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="/shared/bootstrap/bootstrap.css" />
    <script src="/shared/bootstrap/bootstrap.bundle.js"></script>
    <style>
      html,
      body {
        height: 100%;
      }

      body {
        background-color: #2d3a4b;
        display: flex;
        justify-content: center;
        align-items: center;
        color: white;
      }

      body .logincontainer {
        background-color: rgba(0, 0, 0, 0.7);
        height: 400px;
        width: 600px;
        padding: 50px;
      }
    </style>
  </head>
  <body>
    <div class="logincontainer">
      <h2>锋企网站管理系统</h2>
      <form id="loginform">
        <div class="mb-3">
          <label for="username" class="form-label">用户名</label>
          <input type="text" class="form-control" id="username" required />
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">密码</label>
          <input type="password" class="form-control" id="password" required />
        </div>
        <button type="submit" class="btn btn-primary">登录</button>
        <div
          id="loginwarning"
          class="form-text"
          style="display: none; color: red"
        >
          用户名和密码不匹配
        </div>
      </form>
    </div>
    <script>
      const loginform = document.querySelector('#loginform')

      loginform.onsubmit = async function (e) {
        loginwarning.style.display = 'none'
        e.preventDefault()
        let res = await fetch(
          `http://localhost:3000/users?username=${username.value}&password=${password.value}`
        ).then((res) => res.json())
        console.log(res)
        if (res.length > 0) {
          localStorage.setItem(
            'token',
            JSON.stringify({
              ...res[0],
              password: '********'
            })
          )

          if (res[0].role === 'admin') {
            location.href = '/views/admin/home/index.html'
          } else {
            location.href = '/views/web/home/index.html'
          }
        } else {
          loginwarning.style.display = 'block'
        }
      }
    </script>
  </body>
</html>
